<template>
  <LoginDialog ref="loginDialogRef" />

  <div class="qa-wrapper">
    <div class="wrapper-list">
      <!-- 循环生成竖向列表 -->
      <div v-for="(product, index) in productList" :key="product.id" class="vertical-card">
        <el-card :body-style="{ padding: '0px' }">
          <div class="card-content" @click="openDialog(product)">
            <!-- 图片部分 -->
            <img :src="logoImg" class="image" />
            <!-- 文字和操作部分 -->
            <div class="text-content">
              <span style="color: darkorange; font-size: 20px; font-weight: bold">{{ product.limitAmount }}</span><el-tag v-if="product.description && product.description === 'VIP'" type="warning" style="margin-left: 5px; font-weight: bold">{{ product.description }}</el-tag>
              <el-tag v-else-if="product.description && product.description === 'SVIP'" type="danger" style="margin-left: 5px; font-weight: bold">{{ product.description }}</el-tag>
              <div>
                <el-rate v-model="rate" disabled text-color="#ff9900"> </el-rate>
              </div>
              <div class="bottom clearfix">
                <el-button type="primary">点击申请</el-button>
              </div>
            </div>
          </div>
        </el-card>
      </div>
    </div>
    <!-- 申请弹窗 -->
    <el-dialog
      v-if="selectedProduct"
      v-model="dialogVisible"
      :title="`申请 （${selectedProduct.limitAmount || ''}）`"
      :width="isMobile ? '380px' : '600px'"
      class="custom-dialog"
    >
      <el-form ref="formRef" label-position="right" :model="form" :rules="rules" style="margin-top: 5px" scrollable>
        <el-form-item label="周期" prop="weekNum" label-width="100px">
          <el-select v-model="form.weekNum" placeholder="请选择周期">
            <el-option label="12周" value="12"></el-option>
            <el-option label="8周" value="8"></el-option>
            <el-option label="4周" value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="姓  名" prop="name" label-width="100px">
          <el-input v-model="form.name" maxlength="50" />
        </el-form-item>
        <el-form-item label="身份证" prop="idCard" label-width="100px">
          <el-input v-model="form.idCard" maxlength="100" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone" label-width="100px">
          <el-input v-model="form.phone" maxlength="20" />
        </el-form-item>
        <el-form-item label="微信号" prop="wechat" label-width="100px">
          <el-input v-model="form.wechat" maxlength="50" />
        </el-form-item>
        <el-form-item label="卡号" prop="bankNum" label-width="100px">
          <el-input v-model="form.bankNum" maxlength="100" />
        </el-form-item>
        <el-form-item label="户籍地址" prop="domicile" label-width="100px">
          <el-input v-model="form.domicile" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea" maxlength="300" />
        </el-form-item>
        <el-form-item label="现住宅地址" prop="address" label-width="100px">
          <el-input v-model="form.address" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea" maxlength="300" />
        </el-form-item>
        <el-form-item label="公司" prop="org" label-width="100px">
          <el-input v-model="form.org" maxlength="200" />
        </el-form-item>
        <el-form-item label="公司地址" prop="orgAddress" label-width="100px">
          <el-input v-model="form.orgAddress" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea" maxlength="300" />
        </el-form-item>
        <el-form-item label="公司电话" prop="orgTel" label-width="100px">
          <el-input v-model="form.orgTel" maxlength="100" />
        </el-form-item>
        <el-form-item label="紧急联系人(1)" prop="contact1" >
          <span>
          <el-input v-model="form.contact1" maxlength="50" style="width: 100px;"/>
          <el-select style="width: 90px; margin-left: 5px;" v-model="form.contact1Id" placeholder="关系">
              <el-option label="父亲" value="父亲"></el-option>
              <el-option label="母亲" value="母亲"></el-option>
              <el-option label="配偶" value="配偶"></el-option>
              <el-option label="朋友" value="朋友"></el-option>
          </el-select>
        </span>
        </el-form-item>
        <el-form-item label="联系人电话" prop="contactTel1" >
          <el-input v-model="form.contactTel1" maxlength="50" />
        </el-form-item>
        <el-form-item label="紧急联系人(2)" prop="contact2" >
          <el-input v-model="form.contact2" maxlength="50" style="width: 100px;"/>
          <el-select style="margin-left: 5px; width: 90px;" v-model="form.contact2Id" placeholder="关系">
            <el-option label="父亲" value="父亲"></el-option>
            <el-option label="母亲" value="母亲"></el-option>
              <el-option label="配偶" value="配偶"></el-option>
              <el-option label="朋友" value="朋友"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系人电话" prop="contactTel2" >
          <el-input v-model="form.contactTel2" maxlength="50" />
        </el-form-item>
        <el-form-item label="紧急联系人(3)" prop="contact3" >
          <el-input v-model="form.contact3" maxlength="50" style="width: 100px;"/>
          <el-select style="margin-left: 5px; width: 90px;" v-model="form.contact3Id" placeholder="关系">
            <el-option label="父亲" value="父亲"></el-option>
            <el-option label="母亲" value="母亲"></el-option>
              <el-option label="配偶" value="配偶"></el-option>
              <el-option label="朋友" value="朋友"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系人电话" prop="contactTel3" >
          <el-input v-model="form.contactTel3" maxlength="50" />
        </el-form-item>
        <el-form-item label="支付宝芝麻分截图" prop="zfbUrl" label-width="150px">
          <el-upload
            class="avatar-uploader"
            :action="uploadURL"
            :http-request="(file : any) => submitUpload(file, 'zfbUrl')"
            :show-file-list="false"
            :on-success="(response: any, uploadFile: any) => handleFileSuccess(response, uploadFile, 'zfbUrl')"
            :before-upload="(rawFile: any) => beforeFileUpload(rawFile, 'zfbUrl')"
          >
            <!-- 展示已选择的图片 -->
            <img v-if="zfbObjectUrl" :src="zfbObjectUrl" class="avatar" />
            <!-- 未选择图片时显示添加图标 -->
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="公积金首页明细截图" prop="gjjUrl" label-width="150px">
          <el-upload
            class="avatar-uploader"
            :action="uploadURL"
            :http-request="(file: any) => submitUpload(file, 'gjjUrl')"
            :show-file-list="false"
            :on-success="(response: any, uploadFile: any) => handleFileSuccess(response, uploadFile, 'gjjUrl')"
            :before-upload="(rawFile: any) => beforeFileUpload(rawFile, 'gjjUrl')"
          >
            <img v-if="gjjObjectUrl" :src="gjjObjectUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="身份证正面" prop="idFrontUrl" label-width="130px">
          <el-upload
            class="avatar-uploader"
            :action="uploadURL"
            :http-request="(file: any) => submitUpload(file, 'idFrontUrl')"
            :show-file-list="false"
            :on-success="(response: any, uploadFile: any) => handleFileSuccess(response, uploadFile, 'idFrontUrl')"
            :before-upload="(rawFile: any) => beforeFileUpload(rawFile, 'idFrontUrl')"
          >
            <img v-if="idFrontObjectUrl" :src="idFrontObjectUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="身份证反面" prop="idBackUrl" label-width="130px">
          <el-upload
            class="avatar-uploader"
            :action="uploadURL"
            :http-request="(file: any) => submitUpload(file, 'idBackUrl')"
            :show-file-list="false"
            :on-success="(response: any, uploadFile: any) => handleFileSuccess(response, uploadFile, 'idBackUrl')"
            :before-upload="(rawFile: any) => beforeFileUpload(rawFile, 'idBackUrl')"
          >
            <img v-if="idBackObjectUrl" :src="idBackObjectUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="手持身份证图片" prop="idPhotoUrl" label-width="130px">
          <el-upload
            class="avatar-uploader"
            :action="uploadURL"
            :http-request="(file: any) => submitUpload(file, 'idPhotoUrl')"
            :show-file-list="false"
            :on-success="(response: any, uploadFile: any) => handleFileSuccess(response, uploadFile, 'idPhotoUrl')"
            :before-upload="(rawFile: any) => beforeFileUpload(rawFile, 'idPhotoUrl')"
          >
            <img v-if="idPhotoObjectUrl" :src="idPhotoObjectUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false" style="width: 130px">取消</el-button>
        <el-button type="primary" style="width: 130px" @click="submitForm">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import * as httpService from '@/services/apply.service'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/useStore'
import LoginDialog from '@/view/user/LoginDialog.vue'
import logoImg from '@/assets/images/scb.jpg'
import { ApplyModule } from '@/services/modules/apply'
import type { UploadProps, UploadRawFile, UploadFile } from 'element-plus'
import axios from 'axios'
// 检测是否为移动端
const isMobile = ref(false)
const checkIsMobile = () => {
  const userAgent = navigator.userAgent.toLowerCase()
  const mobileKeywords = ['android', 'iphone', 'ipad', 'ipod']
  return mobileKeywords.some((keyword) => userAgent.includes(keyword))
}
const userStore = useUserStore()
const productList = ref<ApplyModule.ProductListVo[]>([])
const dialogVisible = ref(false)
const selectedProduct = ref<ApplyModule.ProductListVo>() // 防止undefined
const formRef = ref<any>(null)
const uploadURL = ref<string>('')
const uploadConfig = ref<ApplyModule.UploadFileUrlConifg>()
const rate = ref(5)
const form = ref<ApplyModule.AddApplyRecordForm>({
  id: undefined,
  productId: undefined,
  name: '',
  idCard: '',
  phone: '',
  wechat: '',
  org: '',
  orgAddress: '',
  orgTel: '',
  contact1: '',
  contactTel1: '',
  contact2: '',
  contactTel2: '',
  contact3: '',
  contactTel3: '',
  zfbUrl: undefined,
  gjjUrl: undefined,
  idFrontUrl: undefined,
  idBackUrl: undefined,
  idPhotoUrl: undefined,
  bankNum: '',
  domicile: '',
  address: '',
  weekNum: 12,
})
const loginDialogRef = ref<any>(null)

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  idCard: [{ required: true, message: '请输入身份证号', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  wechat: [{ required: true, message: '请输入微信号', trigger: 'blur' }],
  address: [{ required: true, message: '请输入现居住地址', trigger: 'blur' }],
  domicile: [{ required: true, message: '请输入户籍地址', trigger: 'blur' }],
  bankNum: [{ required: true, message: '请输入卡号', trigger: 'blur' }],
  org: [{ required: true, message: '请输入公司名称', trigger: 'blur' }],
  orgAddress: [{ required: true, message: '请输入公司地址', trigger: 'blur' }],
  orgTel: [{ required: true, message: '请输入公司电话', trigger: 'blur' }],
  contact1: [{ required: true, message: '请输入紧急联系人1姓名', trigger: 'blur' }],
  contactTel1: [{ required: true, message: '请输入紧急联系人1电话', trigger: 'blur' }],
  contact2: [{ required: true, message: '请输入紧急联系人2姓名', trigger: 'blur' }],
  contactTel2: [{ required: true, message: '请输入紧急联系人2电话', trigger: 'blur' }],
  contact3: [{ required: true, message: '请输入紧急联系人3姓名', trigger: 'blur' }],
  contactTel3: [{ required: true, message: '请输入紧急联系人3电话', trigger: 'blur' }],
  zfbUrl: [{ required: true, message: '请上传支付宝芝麻分截图', trigger: 'change' }],
  gjjUrl: [{ required: true, message: '请上传公积金首页明细截图', trigger: 'change' }],
  idFrontUrl: [{ required: true, message: '请上传身份证正面', trigger: 'change' }],
  idBackUrl: [{ required: true, message: '请上传身份证反面', trigger: 'change' }],
  idPhotoUrl: [{ required: false, message: '请上传手持身份证图片', trigger: 'change' }],
  weekNum: [{ required: true, message: '请选择还款周期', trigger: 'change' }],
}

const zfbObjectUrl = ref('')
const zfbFile = ref<UploadRawFile>()
const gjjObjectUrl = ref('')
const gjjFile = ref<UploadRawFile>()
const idFrontObjectUrl = ref('')
const idFrontFile = ref<UploadRawFile>()
const idBackObjectUrl = ref('')
const idBackFile = ref<UploadRawFile>()
const idPhotoObjectUrl = ref('')
const idPhotoFile = ref<UploadRawFile>()

// 获取产品列表
const fetchProductList = async () => {
  try {
    const response = await httpService.getProductList()
    productList.value = response.data || []
  } catch (error) {
    ElMessage.error('获取产品列表失败！')
  }
}

// 打开弹窗
const openDialog = (product: any) => {
  // 检查是否已登录
  if (!userStore.authInfo) {
    loginDialogRef.value?.openDialog() // 使用 `?.` 避免 `null` 报错
    return
  }
  selectedProduct.value = { ...product } // 确保数据正确
  dialogVisible.value = true
}

// **提交表单**
const submitForm = () => {
  formRef.value.validate(async (valid: boolean) => {
    if (!valid) {
      ElMessage.error('请填写完整信息')
      return
    }
    try {
      if (!selectedProduct.value || !selectedProduct.value.id) {
        return
      }
      if (!form.value.contact1Id || !form.value.contact2Id) {
        ElMessage.error('请选择与紧急联系人的关系');
        return 
      }
      const applyData = {
        ...form.value,
        productId: selectedProduct.value.id, // 关联产品
      }
      if (form.value.id) {
        await httpService.updateApplyRecord(applyData) // 修改记录
        ElMessage.success('更新成功！')
      } else {
        await httpService.addApplyRecord(applyData) // 新增记录
        ElMessage.success('提交成功！')
        // 清空表单数据
        form.value = {
          id: undefined,
          productId: undefined,
          name: '',
          idCard: '',
          phone: '',
          wechat: '',
          org: '',
          orgAddress: '',
          orgTel: '',
          contact1: '',
          contactTel1: '',
          contact2: '',
          contactTel2: '',
          contact3: '',
          contactTel3: '',
          zfbUrl: undefined,
          gjjUrl: undefined,
          idFrontUrl: undefined,
          idBackUrl: undefined,
          idPhotoUrl: undefined,
          bankNum: '',
          domicile: '',
          address: '',
          weekNum: 12,
        }
      }
      dialogVisible.value = false
    } catch (error) {
      ElMessage.error('提交失败，请稍后重试')
    }
  })
}

async function submitUpload(file: any, field: string) {
  if (!userStore.authInfo || !userStore.authInfo.id) {
    ElMessage.error('用户未登录！请重新登录后重试')
    return
  }
  const fileName = `${userStore.authInfo.id}/${Date.now()}_${file.file.name}` // 拼接存储路径
  const res = await httpService.getUploadUrl({ fileName: fileName })
  console.log('请求到uploadUrl', res.data)
  uploadConfig.value = res.data
  uploadURL.value = uploadConfig.value.url

  if (!uploadConfig.value) {
    const res = await httpService.getUploadUrl(file.name)
    uploadConfig.value = res.data
  }
  if (!uploadConfig.value) {
    console.error('没有请求到uploadconfig数据')
    return
  }
  // http请求body部分
  // 一定要按如下顺序设置属性，此顺序与文档之一致。
  // 我之前就是顺序不和文档一样，一直400 拒绝访问，显示The body of your POST request is not well-formed multipart/form-d。
  let formData = new FormData()
  formData.append('key', uploadConfig.value.key)
  formData.append('Signature', uploadConfig.value.authorization)
  formData.append('x-cos-security-token', uploadConfig.value.token)
  formData.append('x-cos-meta-fileid', uploadConfig.value.cosFileId)
  formData.append('file', file.file)

  let url = uploadConfig.value.url
  url = url.replace('https://cos.ap-shanghai.myqcloud.com', '/upload')

  try {
    const axiosResponse = await axios({
      method: 'post',
      url: url,
      data: formData,
      headers: {
        // 注意：这里 axios 会自动根据 formData 设置正确的 Content-Type，手动设置可能会出错
        // 'Content-Type': 'multipart/form-data',
      },
    })

    // 根据不同的字段更新表单中的对应字段值
    switch (field) {
      case 'zfbUrl':
        form.value.zfbUrl = uploadConfig.value.file_id
        break
      case 'gjjUrl':
        form.value.gjjUrl = uploadConfig.value.file_id
        break
      case 'idFrontUrl':
        form.value.idFrontUrl = uploadConfig.value.file_id
        break
      case 'idBackUrl':
        form.value.idBackUrl = uploadConfig.value.file_id
        break
      case 'idPhotoUrl':
        form.value.idPhotoUrl = uploadConfig.value.file_id
        break
      default:
        break
    }

    ElMessage.success('上传成功')
  } catch (err) {
    console.log('uploadFile request err', err)
    ElMessage.error('上传失败，请稍后重试')
  }
}

const beforeFileUpload: (rawFile: UploadRawFile, field: string) => boolean | Promise<boolean> = async (
  rawFile,
  field
) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('上传图片只能是 JPG 或 PNG 格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 6) {
    ElMessage.error('图片不能大于 6MB!')
    return false
  }

  // 根据不同的字段生成对应的临时 URL 和存储文件引用
  switch (field) {
    case 'zfbUrl':
      zfbObjectUrl.value = URL.createObjectURL(rawFile)
      zfbFile.value = rawFile
      break
    case 'gjjUrl':
      gjjObjectUrl.value = URL.createObjectURL(rawFile)
      gjjFile.value = rawFile
      break
    case 'idFrontUrl':
      idFrontObjectUrl.value = URL.createObjectURL(rawFile)
      idFrontFile.value = rawFile
      break
    case 'idBackUrl':
      idBackObjectUrl.value = URL.createObjectURL(rawFile)
      idBackFile.value = rawFile
      break
    case 'idPhotoUrl':
      idPhotoObjectUrl.value = URL.createObjectURL(rawFile)
      idPhotoFile.value = rawFile
      break
    default:
      break
  }

  return true
}

const handleFileSuccess: (response: any, uploadFile: UploadFile, field: string) => void = async (
  response,
  uploadFile,
  field
) => {
  // ElMessage.info('上传成功' + JSON.stringify(response));
}

onMounted(() => {
  isMobile.value = checkIsMobile()
  fetchProductList()
})
</script>

<style scoped>
.qa-wrapper {
  padding: 20px;
}
.el-carousel__item h3 {
  color: #475669;
  font-size: 18px;
  opacity: 0.75;
  line-height: 300px;
  margin: 0;
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n + 1) {
  background-color: #d3dce6;
}

/* 头部样式 */
.header-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 20px;
  text-align: center;
}

/* 卡片容器样式 */
.card-container {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  justify-content: space-between;
}

/* 单个卡片样式 */
.card-item {
  width: 48%;
}

.card {
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 10px;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1); /* 添加阴影 */
  transition: box-shadow 0.3s ease;
}

.card:hover {
  box-shadow: 0px 6px 15px rgba(0, 0, 0, 0.15); /* 鼠标悬停时阴影加深 */
}

/* 卡片内容布局 */
.card-content {
  display: flex;
  align-items: flex-start;
  margin-bottom: 10px;
}

.card-thumb {
  width: 40%;
  height: auto;
  border: 1px solid #ddd;
  border-radius: 8px;
  margin-right: 10px;
}

.card-text {
  flex: 1;
}

/* 卡片标题样式 */
.card-title {
  font-size: 20px;
  font-weight: bold;
  color: #187bf3;
  margin-bottom: 8px;
}

/* 描述文本 */
.card-desc {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

/* 信息字段 */
.card-info {
  font-size: 14px;
  color: #666;
  margin: 5px 0;
}

.card-amount {
  font-size: 21px;
  font-weight: bold;
  color: rgb(238, 130, 71); /* 金额字体颜色 */
  font-weight: bold;
}
.card-desc {
  font-size: 21px;
  font-weight: bold;
  color: rgb(11, 4, 0); /* 金额字体颜色 */
  font-weight: bold;
}

/* 间隔线 */
.card-line {
  height: 1px;
  background-color: #f2f2f2;
  margin: 8px 0;
}
.wrapper-header {
  margin-bottom: 10px;
  padding: 10px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #fff;
  .switch {
    display: flex;
    align-items: center;
    .text {
      font-size: 14px;
      color: #666;
      margin-left: 10px;
    }
  }
  .search {
    .van-button {
      margin-left: 10px;
    }
  }
}

/* 卡片底部样式 */
.card-footer {
  text-align: right;
  margin-top: 10px;
}

.apply-button {
  padding: 6px 12px;
  font-size: 14px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.apply-button:hover {
  background-color: #3079ed;
}

/* 表单样式 */
.custom-dialog {
  max-height: 90vh;
}
/* 竖向卡片整体样式 */
.vertical-card {
  margin-bottom: 20px;
}

/* 卡片内容布局 */
.card-content {
  display: flex;
  align-items: center;
}

/* 图片样式 */
.image {
  margin: 10px 14px 0 10px; /* 图片距离右侧边距 */
  border-radius: 4px; /* 圆角 */
  width: 100px; /* 正方形图片的宽度 */
  height: 100px; /* 正方形图片的高度 */
  object-fit: cover; /* 保持图片比例并覆盖容器 */
  display: block;
}

/* 文字内容样式 */
.text-content {
  padding: 14px;
}

/* 时间样式 */
.time {
  font-size: 13px;
  color: #999;
}

/* 底部操作区域样式 */
.bottom {
  margin-top: 13px;
  line-height: 12px;
}

/* 操作按钮样式 */
.button {
  padding: 0;
  float: right;
}
</style>

<style scoped>
.avatar-uploader .avatar {
  width: 110px;
  height: 110px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 110px;
  height: 110px;
  text-align: center;
}
</style>
